package com.example.cdctest.managecontroller;

import com.example.cdctest.pojo.Config;
import com.example.cdctest.service.ConfigService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/manage/config-setting")
public class ConfigSettingController {

    @Resource
    private ConfigService configService;

    //转发到配置管理列表
    @RequestMapping("config-list")
    public ModelAndView configList(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("configList",configService.findAll());
        modelAndView.addObject("configCount",configService.getConfigCount());
        modelAndView.setViewName("/manage/config-setting/config-list");
        return modelAndView;
    }

    //一键还原默认，修改状态值与默认值一致
    @RequestMapping("reduction")
    public void reduction(){
        configService.reductionValue();
    }

    //根据配置信息的Id,修改配置信息的状态值
    @RequestMapping("updateValue")
    @ResponseBody
    public void updateValue(Integer id, String newVals, String key,HttpServletRequest request){
        ServletContext servletContext=request.getSession().getServletContext();
        List<Config> configList=(List<Config>)servletContext.getAttribute("configs");
        try {
            for (Config config:configList
            ) {
                if(key.equals(config.getKey())){
                   config.setId(id);
                   config.setValue(newVals);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Config config=new Config();
        config.setId(id);
        config.setValue(newVals);
        configService.update(config);
    }
}
